package com.hengpeng.itfinoss.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.fckeditor.handlers.PropertiesLoader;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;

import com.hengpeng.common.configuration.ConfigProvider;
import com.hengpeng.common.configuration.ConfigProviderFactory;
import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinoss.constant.MSConstants;

/**
 * <pre>
 * TODO 文件上传工具类
 * </pre>
 * @author pengfangliang
 * @version 1.0, 2010-11-1
 */
public class UploadUtils
{

	private int image_width;

	private int image_height;

	public final static String upload_file_path = PropertiesLoader.getProperty("connector.userFilesAbsolutePath");

	public final static String upload_file_temp = UploadUtils.upload_file_temp + "/temp/";

	private final static Integer MAX_SIZE = Integer.valueOf(PropertiesLoader.getProperty("image.allowedMaxSize"));

	private final static ConfigProvider<String> cp = ConfigProviderFactory
			.getInstance(Constant.HP_COMMON_PROPERTIES_FILEPATH);

	private static Log logger = LogFactory.getLog(UploadUtils.class);

	public int getImage_height()
	{
		return image_height;
	}

	public void setImage_height(int image_height)
	{
		this.image_height = image_height;
	}

	public int getImage_width()
	{
		return image_width;
	}

	public void setImage_width(int image_width)
	{
		this.image_width = image_width;
	}

	/**
	 * 上传文件
	 * @param request 请求
	 * @param path 图片存储路径
	 * @return 请求的参数对应key-value
	 */
	public Map<String, String> upload(HttpServletRequest request, String path)
	{

		String tempPath = upload_file_temp;
		path = upload_file_path + path;
		createDir(path);
		createDir(tempPath);
		Map<String, String> parameters = new HashMap<String, String>();
		DiskFileItemFactory file = new DiskFileItemFactory();
		file.setSizeThreshold(4096);
		file.setRepository(new File(tempPath));
		ServletFileUpload upfu = new ServletFileUpload(file);
		upfu.setSizeMax(MAX_SIZE);
		List fileItems = null;

		try
		{

			fileItems = upfu.parseRequest(request);

		}
		catch (FileUploadException e)
		{

			logger.error("Error occurs when do method Map<String, String> upload() in UploadUtils.class:\n", e);
			return parameters;
		}

		Iterator fileItr = fileItems.iterator();

		FileItem itme = null;

		while (fileItr.hasNext())
		{

			itme = (FileItem) fileItr.next();

			String fileName = itme.getName();

			if (fileName != null && fileName != "")
			{

				if (!itme.isFormField())
				{

					String temp = resourceFilename(fileName);

					File savefile = new File(path + temp);

					parameters.put(itme.getFieldName(), temp);

					// 文件大小
					parameters.put("filesize", String.valueOf(itme.getSize() / 1024));
					parameters.put("format", itme.getContentType());

					try
					{
						itme.write(savefile);
						// 图片压缩处理 -- 等比压缩
						// ImageZipUtil zipUtil = new ImageZipUtil();
						// zipUtil.setImage_height(this.image_height);
						// zipUtil.setImage_width(this.image_width);
						// zipUtil.zipImageFile(path + temp, Constant.Photo_quality, "");
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}

			}
			else
			{
				if (parameters.containsKey(itme.getFieldName()))
				{
					parameters.put(itme.getFieldName(),
							parameters.get(itme.getFieldName()) + "," + getParameter(itme.getString()));
				}
				else
				{
					String value = getParameter(itme.toString());
					if (value == null || value.trim().length() == 0)
						value = null;
					parameters.put(itme.getFieldName(), value);
				}
			}
		}

		return parameters;
	}

	/**
	 * 上传文件
	 * @param upload
	 * @param path 图片存储路径
	 * @param isMore 是否需要压缩多次
	 * @return
	 */
	public String uploadBySpringMVC(MultipartFile upload, String path, String imageName, boolean isMore)
	{

		path = upload_file_path + path;
		String accessFileName = null;

		createDir(path);
		FileOutputStream fs = null;
		InputStream in = null;
		try
		{
			String fileName = upload.getOriginalFilename().toLowerCase();
			if (fileName != null && fileName.trim().length() != 0)
			{
				String format = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
				if (format.equals("jpg") || format.equals("jpeg") || format.equals("png") || format.equals("gif"))
				{
					if (StringHelper.isEmpty(imageName))
					{
						accessFileName = resourceFilename(fileName);
					}
					else
					{
						accessFileName = imageName + "." + format;
					}
					fs = new FileOutputStream(path + File.separator + accessFileName);
					in = upload.getInputStream();
					byte[] buffer = new byte[1024];
					int bytesum = 0;
					int byteread = 0;
					while ((byteread = in.read(buffer)) != -1)
					{
						bytesum += byteread;
						fs.write(buffer, 0, byteread);
						fs.flush();
					}
					in.close();
					fs.close();
				}
				else
				{
					throw new RuntimeException("不支持的图片格式.");
				}

			}

		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				in.close();
				fs.close();
			}
			catch (Exception ex)
			{
				ex.printStackTrace();
			}
		}
		// 图片压缩处理 -- 等比压缩
		if (isMore)
		{
			String[] sizeArray = cp.getConfigByPrimaryKey("ai306.code.image.size").split(",");
			CompressImageUtil imageUtil = new CompressImageUtil();
			if (sizeArray != null)
			{
				for (String size : sizeArray)
				{
					String inputDir = path + File.separator, outputDir = path + File.separator
							+ PropertiesLoader.getIconPath() + File.separator;
					String outputFileName = accessFileName.substring(0, accessFileName.indexOf(".")) + "_" + size
							+ accessFileName.substring(accessFileName.indexOf("."), accessFileName.length());
					imageUtil.compressPic(inputDir, outputDir, accessFileName, outputFileName,
							Integer.parseInt(size.split("x")[0]), Integer.parseInt(size.split("x")[1]), true);
				}
			}
		}
		else
		{
			ImageZipUtil zipUtil = new ImageZipUtil();
			zipUtil.setImage_height(this.image_height);
			zipUtil.setImage_width(this.image_width);
			zipUtil.zipImageFile(path + File.separator + accessFileName, MSConstants.Photo_quality, "");
		}

		return accessFileName;
	}

	/**
	 * 上传文件
	 * @param upload
	 * @param path 文件存储路径
	 * @return
	 */
	public String uploadFile(MultipartFile upload, String path, String name)
	{
		String accessFileName = null;
		createDir(path);
		FileOutputStream fs = null;
		InputStream in = null;
		try
		{
			String fileName = upload.getOriginalFilename().toLowerCase();
			if (fileName != null && fileName.trim().length() != 0)
			{
				String format = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
				String limit=PropertiesLoader.getProperty("connector.resourceType.file.extensions.allowed");
				if (limit.contains(format))
				{
					if (StringHelper.isEmpty(name))
					{
						accessFileName = resourceFilename(fileName);
					}
					else
					{
						accessFileName = name + "." + format;
					}
					fs = new FileOutputStream(path + File.separator + accessFileName);
					in = upload.getInputStream();
					byte[] buffer = new byte[1024];
					int bytesum = 0;
					int byteread = 0;
					while ((byteread = in.read(buffer)) != -1)
					{
						bytesum += byteread;
						fs.write(buffer, 0, byteread);
						fs.flush();
					}
					in.close();
					fs.close();
				}
				else
				{
					throw new RuntimeException("不支持的文件格式.");
				}
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				in.close();
				fs.close();
			}
			catch (Exception ex)
			{
				ex.printStackTrace();
			}
		}
		return accessFileName;
	}
	
	
	public String resourceFilename(String filename)
	{
		String lastName = "";
		String newname = "";
		// 获取纯粹的文件名
		int na = (int) (Math.random() * 9999);
		lastName = filename.substring(filename.lastIndexOf("\\") + 1);
		String typeName = "." + lastName.substring(lastName.lastIndexOf(".") + 1);
		newname = new Long(System.currentTimeMillis()).toString() + String.valueOf(na) + typeName;
		return newname;
	}

	public String getShortFileName(String filename)
	{

		return filename.substring(filename.lastIndexOf("\\") + 1);
	}

	public String getParameter(String parameter)
	{

		try
		{
			parameter = new String(parameter.getBytes("iso-8859-1"), "UTF-8");
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}

		return parameter;
	}

	// 删除图片
	public static void deleteFile(String path, String filename)
	{
		File file = new File(upload_file_path + path + filename);
		if (file.exists() && file.isFile())
		{
			file.delete();
		}
	}

	protected static void createDir(final String dir)
	{
		File fileDir = new File(dir);
		if (!fileDir.exists())
			fileDir.mkdirs();
	}
}
